package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){
        log.info("size:{},pageSize:{}",page,pageSize);
        Page CategoryPage1 = new Page(page,pageSize);
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.orderByDesc(Category::getSort);
        categoryService.page(CategoryPage1,categoryLambdaQueryWrapper);
        return R.success(CategoryPage1);
    }
    @PutMapping
    public R<String> editCategory(@RequestBody Category category){
        log.info("id:"+category.getId()+"name:"+category.getName()+"sort:"+category.getSort());
        //LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //categoryLambdaQueryWrapper.eq(category.getId()!=null,Category::getId,category.getId());
        boolean update = categoryService.updateById(category);
        if (update==true)return R.success("修改成功");

        return R.error("修改失败");

    }

    /**
     * 添加菜品分类
     * @param category
     * @return
     *
     */
    @PostMapping
    public R<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        return  R.success("添加成功");
    }
    /**
     * 删除菜品分类
     * 请求网址: http://localhost:8080/category?ids=1630381562530930689
     * 请求方法: DELETE
     * 状态代码: 405
     * 远程地址: [::1]:8080
     * 引荐来源网址政策: strict-origin-when-cross-origin
     */
    @DeleteMapping
    public R<String> deleteCategory(Long ids){

        log.info("ids:{}",ids);
        categoryService.remove(ids);

        return R.error("删除失败");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType()!= null,Category::getType,category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);


    }


}
